package com.yst.webplugin.additional.mask;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class MaskConfigUtil {
    public static FieldMaskConfigItem fromAnnotation(Mask annotation){
        try {
            return new FieldMaskConfigItem(annotation.fieldName(), annotation.handler().newInstance());
        }
        catch (Exception e){
            e.printStackTrace();
            //ignore exception
        }
        return null;
    }

    public static List<FieldMaskConfigItem> fromAnnotation(Mask.List annotation){
        List<FieldMaskConfigItem> result=new ArrayList<>();
        Mask[] masks=annotation.value();
        for(Mask mask:masks){
            FieldMaskConfigItem configItem=fromAnnotation(mask);
            if (Objects.nonNull(configItem)) {
                result.add(configItem);
            }
        }
        return result;
    }

    public static List<FieldMaskConfigItem> fromField(Field field){
        List<FieldMaskConfigItem> result=new ArrayList<>();
        Mask mask= field.getAnnotation(Mask.class);
        if (Objects.nonNull(mask)){
            result.add(fromAnnotation(mask));
        }

        Mask.List maskList=field.getAnnotation(Mask.List.class);
        if (Objects.nonNull(maskList)){
            result.addAll(fromAnnotation(maskList));
        }

        return result;
    }
}
